﻿package iamjason.remoting
{
	import flash.events.EventDispatcher;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.ObjectEncoding;
	import flash.events.Event;
	import flash.net.registerClassAlias;
	import kgcheck.playData;
	/**
	 * ...
	 * @author Jason Tseng
	 */
	public class JRemoting extends EventDispatcher {
		private static var _PROXY:String = "http://www.medialand.com.tw/Gateway.aspx";
		private var _data:*;
		private var _nc:NetConnection;
		private var _responder:Responder;
		private var _onComplete:Function;
		private var _onError:Function;
		
		public static function get PROXY():String {
			return _PROXY;
		}
		public static function set PROXY(pStr:String):void {
			_PROXY = pStr;
		}
		public function JRemoting(pFunctionName:String, onComplete:Function = null, onError:Function = null, ...args) {
			if (onComplete != null) {
				_onComplete = onComplete;
				this.addEventListener(Event.COMPLETE, _onComplete);
			}
			if (onError != null) {
				_onError = onError;
				this.addEventListener(Event.CANCEL, _onError);
			}
			_nc = new NetConnection();
			_nc.objectEncoding = ObjectEncoding.AMF3;
			_nc.connect(JRemoting.PROXY);
			_responder = new Responder(responseComplete, responseError);
			var _argArray:Array = [pFunctionName, _responder];
			_argArray = _argArray.concat(args);
			_nc.call.apply(null, _argArray);
		}
		private function responseComplete(pObj:Object):void {
			_data = pObj;
			this.dispatchEvent(new Event(Event.COMPLETE));
			destroy();
		}
		private function responseError(info:Object):void {
			//trace(info);
			for (var itm in info) {
				trace(itm + " = " + info[itm]);
			}
			this.dispatchEvent(new Event(Event.CANCEL));
			removeEvents();
		}
		private function removeEvents():void {
			if (_onComplete  != null) {
				this.removeEventListener(Event.COMPLETE, _onComplete);
				_onComplete = null;
			}
			if (_onError  != null) {
				this.removeEventListener(Event.CANCEL, _onError);
				_onError = null;
			}
		}
		public function destroy():void {
			removeEvents();
			_responder = null;
			_nc = null;
			_data = null;
		}
		public function get data():* {
			return _data;
		}
	}

}